require "digest/sha2"

class Worker < ActiveRecord::Base
  validates_uniqueness_of :name
  validates_uniqueness_of :email

  validates_presence_of :name
  validates_presence_of :email
  validates_presence_of :password
  validates_presence_of :salt
 
  has_and_belongs_to_many :routes
  has_many :comments

  def <=>(x)
    self.name <=> x.name
  end

  def is_schorsch?
    if admin >= 1
      return true
    else
      return false
    end
  end
  
  def is_admin?
    if admin >= 2
      return true
    else
      return false
    end
  end

  def is_creator?(route)
    self.routes.include?(route)
  end

  def self.authenticate(email, password)
    worker = Worker.find_by_email(email)
    return nil if !worker
    
    if worker.password == do_create_hash(worker, password) 
      return worker
    else
      return nil
    end
  end
  
  def to_link
    "<a href=\"/workers/#{self.id}\" >#{self.name}</a>".html_safe
  end
 
  def new_password(password)
    self.password = (Digest::SHA2.new << (self.salt + password)).to_s
    self.save
  end 
private
  def self.do_create_hash(worker, password)
    (Digest::SHA2.new << worker.salt + password).to_s
  end
end
